<template>
  <tn-popup 
    mode="center" 
    :value="value" 
    @close="onClose" 
    :mask-closeable="true" 
    width="600rpx" 
	:z-index="999999999"
    :zoom="true" 
	backgroundColor="transparent"
    :border-radius="20"
  >
    <view class="filter-content" v-if="tempOptions">
      <view class="filter-header">
        <view class="filter-title">
          <text class="filter-title-icon tn-icon-filter"></text>
          <text>筛选选项</text>
        </view>
        <button class="filter-close" @tap="onClose">
          <text class="tn-icon-close"></text>
        </button>
      </view>
      
      <scroll-view 
        scroll-y="true" 
        class="filter-scroll-area" 
        :show-scrollbar="false"
        :enhanced="true"
        :bounces="true"
        :fast-deceleration="true"
        :scroll-top="scrollTopFilter"
      >
        <!-- 性别筛选 -->
        <view class="filter-group">
          <view class="filter-group-title">
            <text class="filter-group-icon tn-icon-sex-male"></text>
            <text>性别</text>
          </view>
          <view class="filter-option-grid">
            <view 
              :class="['filter-option', tempOptions && tempOptions.gender === 'all' ? 'active' : '']" 
              @tap="setFilterOption('gender', 'all')"
            >不限</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.gender === 'female' ? 'active' : '']" 
              @tap="setFilterOption('gender', 'female')"
            >女生</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.gender === 'male' ? 'active' : '']" 
              @tap="setFilterOption('gender', 'male')"
            >男生</view>
          </view>
        </view>
        
        <!-- 年龄筛选 -->
        <!-- <view class="filter-group">
          <view class="filter-group-title">
            <text class="filter-group-icon tn-icon-calendar"></text>
            <text>年龄范围</text>
          </view>
          <view class="age-range-selector">
            <view class="age-selector">
              <view class="age-label">最小年龄</view>
              <view class="age-controls">
                <view 
                  class="age-btn age-btn-minus" 
                  @tap="adjustAge('min', -1)"
                  :class="{'disabled': tempOptions.ageRange[0] <= 18}"
                >
                  <text class="tn-icon-reduce"></text>
                </view>
                <view class="age-value">{{tempOptions.ageRange[0]}}岁</view>
                <view 
                  class="age-btn age-btn-plus" 
                  @tap="adjustAge('min', 1)"
                  :class="{'disabled': tempOptions.ageRange[0] >= tempOptions.ageRange[1] - 1}"
                >
                  <text class="tn-icon-add"></text>
                </view>
              </view>
            </view>
            
            <view class="age-selector">
              <view class="age-label">最大年龄</view>
              <view class="age-controls">
                <view 
                  class="age-btn age-btn-minus" 
                  @tap="adjustAge('max', -1)"
                  :class="{'disabled': tempOptions.ageRange[1] <= tempOptions.ageRange[0] + 1}"
                >
                  <text class="tn-icon-reduce"></text>
                </view>
                <view class="age-value">{{tempOptions.ageRange[1]}}岁</view>
                <view 
                  class="age-btn age-btn-plus" 
                  @tap="adjustAge('max', 1)"
                  :class="{'disabled': tempOptions.ageRange[1] >= 50}"
                >
                  <text class="tn-icon-add"></text>
                </view>
              </view>
            </view>
          </view>
        </view> -->
        
        <!-- 距离筛选 -->
        <view class="filter-group">
          <view class="filter-group-title">
            <text class="filter-group-icon tn-icon-location"></text>
            <text>距离</text>
          </view>
          <view class="filter-option-grid">
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 0 ? 'active' : '']" 
              @tap="setFilterOption('distance', 0)"
            >不限</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 1 ? 'active' : '']" 
              @tap="setFilterOption('distance', 1)"
            >1公里内</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 5 ? 'active' : '']" 
              @tap="setFilterOption('distance', 5)"
            >5公里内</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 10 ? 'active' : '']" 
              @tap="setFilterOption('distance', 10)"
            >10公里内</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 20 ? 'active' : '']" 
              @tap="setFilterOption('distance', 20)"
            >20公里内</view>
            <view 
              :class="['filter-option', tempOptions && tempOptions.distance === 50 ? 'active' : '']" 
              @tap="setFilterOption('distance', 50)"
            >50公里内</view>
          </view>
        </view>
        
        <!-- 兴趣筛选 -->
        <!-- <view class="filter-group">
          <view class="filter-group-title">
            <text class="filter-group-icon tn-icon-like"></text>
            <text>兴趣爱好</text>
          </view>
          <view class="loading-tags" v-if="isLoadingTags">
            <view class="loading-spinner"></view>
            <text class="loading-text">加载中...</text>
          </view>
          <view class="filter-option-grid" v-else>
            <view 
              v-for="(tag, i) in tagList" 
              :key="i"
              :class="['filter-option', tempOptions && tempOptions.selectedInterests.includes(tag.name) ? 'active' : '']"
              @tap="toggleInterest(tag.name)"
            >
              {{ tag.name }}
            </view>
          </view>
        </view> -->
        
        <!-- 其他筛选选项 -->
        <view class="filter-group">
          <view class="filter-group-title">
            <text class="filter-group-icon tn-icon-more-horizontal"></text>
            <text>其他选项</text>
          </view>
          <view class="filter-switch">
            <text class="switch-label">只看认证用户</text>
            <tn-switch 
              v-model="tempOptions.verifiedOnly"
              activeColor="#B3F73C"
              inactiveColor="#333333"
              :size="40"
              class="custom-switch"
            ></tn-switch>
          </view>
          <view class="filter-switch">
            <text class="switch-label">只看VIP用户</text>
            <tn-switch 
              v-model="tempOptions.vipOnly"
              activeColor="#B3F73C"
              inactiveColor="#333333"
              :size="40"
              class="custom-switch"
            ></tn-switch>
          </view>
        </view>
        
        <!-- 底部占位，确保内容不被按钮遮挡 -->
        <view style="height: 110rpx;"></view>
      </scroll-view>
      
      <!-- 操作按钮 -->
      <view class="filter-actions">
        <view 
          class="filter-reset" 
          @tap="resetFilter"
        >重置</view>
        <view 
          class="filter-apply" 
          @tap="applyFilter"
        >应用</view>
      </view>
    </view>
  </tn-popup>
</template>

<script>
import { getTagList } from '@/api/user/index.js';

export default {
  name: 'FilterPopup',
  
  props: {
    value: {
      type: Boolean,
      default: false
    },
    filterOptions: {
      type: Object,
      default: () => ({
        ageRange: [18, 50],
        gender: 'all',
        distance: 0,
        onlineOnly: false,
        verifiedOnly: false,
        withInterestsOnly: false,
        vipOnly: false,
        selectedInterests: [],
        selectedTagIds: []
      })
    },
    interests: {
      type: Array,
      default: () => ['游戏', '电影', '旅行', '美食', '摄影', '运动', '音乐', '阅读', '动漫', '宠物', '健身', '编程']
    }
  },
  
  data() {
    return {
      // 临时存储筛选器
      tempOptions: {
        ageRange: [18, 50],
        gender: 'all',
        distance: 0,
        onlineOnly: false,
        verifiedOnly: false,
        withInterestsOnly: false,
        vipOnly: false,
        selectedInterests: [],
        selectedTagIds: []
      },
      // 滚动位置控制
      scrollTopFilter: 0,
      // 标签列表和加载状态
      tagList: [],
      isLoadingTags: false
    }
  },
  
  created() {
    // 确保组件创建时就初始化tempOptions
    this.initTempOptions();
  },
  
  watch: {
    value(newVal) {
      if (newVal) {
        // 确保在弹窗打开时重新初始化选项
        this.initTempOptions();
        // 加载标签数据
        this.loadTagList();
        // 重置滚动位置
        setTimeout(() => {
          this.scrollTopFilter = 0;
        }, 100);
      }
    },
    
    // 监听filterOptions的变化
    filterOptions: {
      handler(newOptions) {
        if (this.value && newOptions) {
          // 当弹窗打开且filterOptions发生变化时重新初始化
          this.initTempOptions();
        }
      },
      deep: true
    }
  },
  
  methods: {
    // 初始化临时选项
    initTempOptions() {
      try {
        // 深拷贝当前筛选选项
        if (this.filterOptions) {
          this.tempOptions = JSON.parse(JSON.stringify(this.filterOptions));
        } else {
          // 如果filterOptions不存在，初始化默认值
          this.tempOptions = {
            ageRange: [18, 50],
            gender: 'all',
            distance: 0,
            onlineOnly: false,
            verifiedOnly: false,
            withInterestsOnly: false,
            vipOnly: false,
            selectedInterests: [],
            selectedTagIds: []
          };
        }
        
        // 确保所有必需的属性都存在
        if (!this.tempOptions.selectedInterests) {
          this.tempOptions.selectedInterests = [];
        }
        if (!this.tempOptions.selectedTagIds) {
          this.tempOptions.selectedTagIds = [];
        }
        
        // 确保布尔值属性始终存在
        this.tempOptions.onlineOnly = !!this.tempOptions.onlineOnly;
        this.tempOptions.verifiedOnly = !!this.tempOptions.verifiedOnly;
        this.tempOptions.vipOnly = !!this.tempOptions.vipOnly;
        this.tempOptions.withInterestsOnly = !!this.tempOptions.withInterestsOnly;
        
      } catch (error) {
        console.error('初始化筛选选项时出错:', error);
        // 出错时使用默认值
        this.tempOptions = {
          ageRange: [18, 50],
          gender: 'all',
          distance: 0,
          onlineOnly: false,
          verifiedOnly: false,
          withInterestsOnly: false,
          vipOnly: false,
          selectedInterests: [],
          selectedTagIds: []
        };
      }
    },
    
    // 加载标签列表
    loadTagList() {
      // 如果标签列表已经加载过，不重复加载
      if (this.tagList.length > 0) {
        return;
      }
      
      this.isLoadingTags = true;
      
      getTagList().then(response => {
        if (response && Array.isArray(response)) {
          // 直接使用返回的标签数据
          this.tagList = response.map(tag => ({
            id: tag.id,
            name: tag.name,
            selected: tag.selected || false
          }));
        } else if (response && response.code === 0 && Array.isArray(response.data)) {
          // 处理包含在 response.data 中的标签数据
          this.tagList = response.data.map(tag => ({
            id: tag.id,
            name: tag.name,
            selected: tag.selected || false
          }));
        }
        this.isLoadingTags = false;
      }).catch(error => {
        console.error('获取标签列表失败:', error);
        // 出错时使用props中传入的兴趣作为备用
        this.tagList = this.interests.map((name, index) => ({
          id: index,
          name: name,
          selected: false
        }));
        this.isLoadingTags = false;
      });
    },
    
    // 关闭弹窗
    onClose() {
      this.$emit('input', false);
      this.$emit('close');
      // 不要设置为null，避免渲染时出现引用错误
      // this.tempOptions = null;
    },
    
    // 设置筛选选项
    setFilterOption(key, value) {
      // 确保tempOptions存在
      if (!this.tempOptions) {
        this.initTempOptions();
      }
      
      this.tempOptions[key] = value;
      
      // 触发界面更新
      this.tempOptions = { ...this.tempOptions };
    },
    
    // 切换兴趣标签
    toggleInterest(interest) {
      // 确保tempOptions存在
      if (!this.tempOptions) {
        this.initTempOptions();
      }
      
      // 确保必要的数组存在
      if (!this.tempOptions.selectedInterests) {
        this.tempOptions.selectedInterests = [];
      }
      if (!this.tempOptions.selectedTagIds) {
        this.tempOptions.selectedTagIds = [];
      }
      
      // 找到当前标签对象
      const tagObj = this.tagList.find(tag => tag.name === interest);
      if (!tagObj) return;
      
      const index = this.tempOptions.selectedInterests.indexOf(interest);
      if (index > -1) {
        // 移除标签名称
        this.tempOptions.selectedInterests.splice(index, 1);
        // 移除对应的标签ID
        const idIndex = this.tempOptions.selectedTagIds.indexOf(tagObj.id);
        if (idIndex > -1) {
          this.tempOptions.selectedTagIds.splice(idIndex, 1);
        }
      } else {
        // 添加标签名称
        this.tempOptions.selectedInterests.push(interest);
        // 添加标签ID
        this.tempOptions.selectedTagIds.push(tagObj.id);
      }
      
      // 触发界面更新
      this.tempOptions = { ...this.tempOptions };
    },
    
    // 重置筛选
    resetFilter() {
      this.tempOptions = {
        ageRange: [18, 50],
        gender: 'all',
        distance: 0,
        onlineOnly: false,
        verifiedOnly: false,
        withInterestsOnly: false,
        vipOnly: false,
        selectedInterests: [],
        selectedTagIds: []
      };
      
      this.$emit('reset');
    },
    
    // 应用筛选
    applyFilter() {
      this.$emit('apply', this.tempOptions);
      this.onClose();
    },
    
    // 调整年龄范围
    adjustAge(type, change) {
      // 确保tempOptions存在
      if (!this.tempOptions) {
        this.initTempOptions();
      }
      
      // 调整年龄范围
      if (type === 'min') {
        this.tempOptions.ageRange[0] = Math.max(18, Math.min(this.tempOptions.ageRange[0] + change, this.tempOptions.ageRange[1] - 1));
      } else if (type === 'max') {
        this.tempOptions.ageRange[1] = Math.min(50, Math.max(this.tempOptions.ageRange[1] + change, this.tempOptions.ageRange[0] + 1));
      }
      
      // 触发界面更新
      this.tempOptions = { ...this.tempOptions };
    }
  }
}
</script>

<style lang="scss" scoped>
/* 筛选弹窗样式 */
.filter-content {
  width: 100%;
  background-color: #121212;
  position: relative;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  height: 60vh; /* 固定高度，解决真机上弹窗不能滚动问题 */
  max-height: 1000rpx; /* 增加最大高度限制 */
  border: 2rpx solid rgba(179, 247, 60, 0.15);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.6);
  
  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 30rpx 15rpx;
    margin-bottom: 15rpx;
    flex-shrink: 0;
    
    .filter-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #ffffff;
      position: relative;
      display: flex;
      align-items: center;
      gap: 10rpx;
      
      .filter-title-icon {
        color: #B3F73C;
        font-size: 40rpx;
      }
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        bottom: -10rpx;
        width: 40rpx;
        height: 4rpx;
        background: linear-gradient(90deg, #B3F73C, #00C4FF);
        border-radius: 3rpx;
      }
    }
    
    .filter-close {
      background: none;
      border: none;
      color: #e0e0e0;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      padding: 0;
      margin: 0;
      transition: all 0.2s;
      
      &:active {
        background-color: rgba(179, 247, 60, 0.1);
        color: #B3F73C;
        transform: scale(0.95);
      }
    }
  }
  
  .filter-scroll-area {
    flex: 1;
    padding: 0 30rpx;
    height: calc(100% - 180rpx); /* 设置明确的高度，减去头部和底部的高度 */
    -webkit-overflow-scrolling: touch; /* 增强iOS上的滚动体验 */
  }
  
  .filter-group {
    margin-bottom: 25rpx;
    
    .filter-group-title {
      font-size: 30rpx;
      font-weight: 600;
      margin-bottom: 15rpx;
      display: flex;
      align-items: center;
      color: #ffffff;
      
      .filter-group-icon {
        margin-right: 16rpx;
        color: #B3F73C;
      }
    }
    
    .filter-option-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15rpx;
      
      .filter-option {
        padding: 12rpx 0;
        border-radius: 20rpx;
        text-align: center;
        background-color: #1a1a1a;
        color: #aaa;
        font-size: 26rpx;
        transition: all 0.2s;
        
        &:active {
          transform: scale(0.95);
        }
        
        &.active {
          background: linear-gradient(45deg, #B3F73C, #00C4FF);
          color: #080808;
          border-color: transparent;
          font-weight: 600;
        }
      }
    }
    
    .age-range-selector {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 15rpx 0 20rpx;
      gap: 20rpx;
      
      .age-selector {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: #1a1a1a;
        border-radius: 12rpx;
        padding: 15rpx;
        border: 1rpx solid rgba(179, 247, 60, 0.1);
        
        .age-label {
          font-size: 26rpx;
          font-weight: 600;
          margin-bottom: 15rpx;
          color: #ffffff;
        }
        
        .age-controls {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          
          .age-btn {
            background: #222222;
            border: 1rpx solid rgba(179, 247, 60, 0.2);
            color: #e0e0e0;
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            
            text {
              font-size: 24rpx;
              font-weight: bold;
            }
            
            &:active {
              color: #B3F73C;
              border-color: rgba(179, 247, 60, 0.6);
              transform: scale(0.95);
              background: #333333;
            }
            
            &.disabled {
              color: #444444;
              border-color: rgba(255, 255, 255, 0.1);
              background: #1c1c1c;
              cursor: not-allowed;
            }
          }
          
          .age-value {
            font-size: 30rpx;
            font-weight: bold;
            background: linear-gradient(45deg, #B3F73C, #00C4FF);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-align: center;
            min-width: 80rpx;
            padding: 0 10rpx;
          }
        }
      }
    }
    
    .filter-switch {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 18rpx;
      background-color: #1a1a1a;
      padding: 16rpx 24rpx;
      border-radius: 12rpx;
      transition: all 0.2s;
      
      &:active {
        background-color: #222222;
        border-color: rgba(179, 247, 60, 0.2);
      }
      
      .switch-label {
        font-size: 26rpx;
        color: #e0e0e0;
      }

      .custom-switch {
        ::v-deep .tn-switch__node {
          background-color: #fff !important;
        }
        
        ::v-deep .tn-switch--on {
          background-color: #B3F73C !important;
          border-color: #B3F73C !important;
        }
        
        ::v-deep .tn-switch--off {
          background-color: #333333 !important;
          border-color: #444444 !important;
        }
      }

      /* 增强开关样式 */
      ::v-deep .tn-switch {
        transform: scale(1.2);
      }
    }
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background-color: #121212;
    z-index: 10;
    border-radius: 0 0 20rpx 20rpx;
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.3);
    flex-shrink: 0; /* 防止按钮被压缩 */
    
    .filter-reset, .filter-apply {
      flex: 1;
      height: 80rpx;
      transition: all 0.2s;
      font-size: 30rpx;
      font-weight: 500;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .filter-reset {
      background-color: transparent;
      color: #e0e0e0;
      border: 2rpx solid rgba(179, 247, 60, 0.2);
      
      &:active {
        color: #B3F73C;
        border-color: rgba(179, 247, 60, 0.4);
      }
    }
    
    .filter-apply {
      background: linear-gradient(45deg, #B3F73C, #00C4FF);
      color: #080808;
      box-shadow: 0 4rpx 12rpx rgba(179, 247, 60, 0.3);
      
      &:active {
        opacity: 0.9;
      }
    }
  }

  /* 添加标签加载中样式 */
  .loading-tags {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30rpx 0;
    
    .loading-spinner {
      width: 40rpx;
      height: 40rpx;
      border: 4rpx solid rgba(179, 247, 60, 0.2);
      border-top: 4rpx solid #B3F73C;
      border-radius: 50%;
      animation: loading-spin 1s linear infinite;
      margin-bottom: 10rpx;
    }
    
    .loading-text {
      font-size: 26rpx;
      color: rgba(255, 255, 255, 0.7);
    }
  }
  
  @keyframes loading-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
}

/* 确保筛选选项在小屏幕上正常显示 */
@media screen and (max-width: 375px) {
  .filter-option-grid {
    .filter-option {
      padding: 10rpx 0;
      font-size: 24rpx;
    }
  }
}
</style> 